/**
 *
 * 入职登记，员工信息维护，员工信息查询的排序弹窗组件
 *
 * props: {
 *      visible: true|false  显示|隐藏,
 *      onClose: function() {}  关闭弹窗钩子,
 *      table: 平台的table对象,
 *      cardTable: 平台的cardTable对象,
 *      onSure: 点击确定按钮的回调,
 *      meta: 平台的meta对象,
 *      templateId: 排序模版对应的模版名称
 * }
 *
 */


import React, {Component} from 'react';

import './index.less';

import {
    base,
    toast
} from 'nc-lightapp-front';

import initSortData from './functions/getInitSortData';
import saveSort from './functions/saveSort';
import cleanSortTable from './functions/cleanSortTable';

import getLanguage from '../../language';

const language = {};

const {
    NCModal,
    NCSelect,
    NCButton,
    NCPopconfirm
} = base;

const {
    Header: NCModalHeader,
    Body: NCModalBody,
    Footer: NCModalFooter
} = NCModal;

const {NCOption} = NCSelect;

let onceInit = false;

class SortModal extends Component {
    constructor(props) {
        super(props);
        props.use.table('sort');

        this.state = {
            allFields: [],
            selectedField: '',
            selectedAscendFlag: true,
            pkHrSort: '',
            language: {}
        };

        this.tableData = {};

        this.closeModal = this.closeModal.bind(this);
        this.showModalHandle = this.showModalHandle.bind(this);
        this.selectChangeHandle = this.selectChangeHandle.bind(this);
        this.addOneRow = this.addOneRow.bind(this);
        this.saveSort = this.saveSort.bind(this);
        this.operateTable = this.operateTable.bind(this);
        this.exchangeTable = this.exchangeTable.bind(this);
        this.moveTableRow = this.moveTableRow.bind(this);
        this.cleanTable = this.cleanTable.bind(this);
        this.getTableData = this.getTableData.bind(this);
        this.beSure = this.beSure.bind(this);
        this.processTemplate = this.processTemplate.bind(this);
        this.deleteRow = this.deleteRow.bind(this);
    }

    componentDidMount() {
        setTimeout(() => {
            this.props.MultiInit.getMultiLang({
                moduleId: 'p6007',
                domainName: 'hrhi',
                callback: (json, status, inlt) => {
                    this.setState({
                        language: json
                    });
                    // 刚进入排序弹窗的的时候 设置的item width不起作用 先这样写
                    this.processTemplate();
                }
            });
        }, 1000);
    }

    deleteRow(text, record, index) {
        const {
            templateId,
            table
        } = this.props;

        table.deleteTableRowsByIndex(templateId, index);
        this.tableData = table.getAllTableData(templateId);
    }

    processTemplate() {
        const {language} = this.state;
        const {meta, templateId} = this.props;
        let template = meta.getMeta();

        template[templateId].items.map((item) => {
            item.width = '135px';
            item.isSort = false;
            item.sorter = null;
            item.itemtype = 'label';
        });

        template[templateId].items.push({
            attrcode: 'opr',
            itemtype: 'customer',
            width: '140px',
            label: language['hi6007-000017'],/* 国际化处理： 操作*/
            visible: true,
            isSort: false,
            sorter: null,
            render: (text, record, index) => {
                return (
                    <div className="sort-operate-box">
                        <a
                            href="javascript:void(0)"
                            onClick={this.operateTable('exchange')(text, record, index)}
                        >
                            {language['hi6007-000022']}{/* 国际化处理： 切换*/}
                        </a>
                        <a
                            href="javascript:void(0)"
                            onClick={this.operateTable('delete')(text, record, index)}
                        >
                            {language['hi6007-000023']}{/* 国际化处理： 删除*/}
                        </a>
                        <a
                            href="javascript:void(0)"
                            onClick={this.operateTable('up')(text, record, index)}
                        >
                            {language['hi6007-000024']}{/* 国际化处理： 上移*/}
                        </a>
                        <a
                            href="javascript:void(0)"
                            onClick={this.operateTable('down')(text, record, index)}
                        >
                            {language['hi6007-000025']}{/* 国际化处理： 下移*/}
                        </a>
                    </div>
                );
            }
        });

        meta.setMeta(template);
    }

    beSure() {
        this.props.onSure && this.props.onSure();
        this.saveSort();
        this.closeModal();
    }

    cleanTable() {
        const {
            templateId,
            table
        } = this.props;

        this.tableData = {
            areacode: templateId,
            rows: []
        };
        this.saveSort()
            .then((res) => {
                if (res.success) {
                    cleanSortTable({
                        pk_hr_sort: this.state.pkHrSort
                    })
                        .then((res) => {
                            if (res.success) {
                                table.setAllTableData(templateId, this.tableData)
                                this.setState({
                                    pkHrSort: res.data.pkHrSort
                                });
                            }
                        });
                }
            })
    }

    operateTable(type) {
        return (text, record, index) => {
            return () => {
                if (type === 'exchange') {
                    this.exchangeTable(text, record, index);
                } else if (type === 'delete') {
                    this.deleteRow(text, record, index)
                } else if (type === 'up' || type === 'down') {
                    this.moveTableRow(text, record, index, type);
                }
            }
        }
    }

    exchangeTable(text, record, index) {
        const {language} = this.state;
        let ascendFlag = this.tableData.rows[index].values['ascend_flag'];

        ascendFlag.value = !ascendFlag.value;
        ascendFlag.display = ascendFlag.value ? language['hi6007-000018'] : language['hi6007-000019'];/* 国际化处理： 升序,降序*/
        this.props.table.setAllTableData('sort', this.tableData)

    }

    moveTableRow(text, record, index, type) {
        const {templateId, table} = this.props;

        if ((type === 'up' && index === 0) || (type === 'down' && index === this.tableData.rows.length - 1)) {
            return;
        }
        let row = this.tableData.rows;

        if (type === 'up') {
            row.splice(index - 1, 0, row.splice(index, 1)[0]);
        } else if (type === 'down') {
            row.splice(index + 1, 0, row.splice(index, 1)[0]);
        }

        table.setAllTableData(templateId, this.tableData)

    }

    saveSort() {
        let postData = {
            func_type: this.props.func_type,
            pk_hr_sort: this.state.pkHrSort,
            sort_con_str: []
        };

        this.tableData.rows.map((item, index) => {
            postData.sort_con_str.push({
                field_seq: index,
                ascend_flag: item.values['ascend_flag'].value,
                field_code: item.values['field_code'].value,
                field_name: item.values['field_code'].display
            });
        });

        return saveSort.call(this, postData).then((res) => {
            toast({
                color: 'success',
                content: this.state.language["hi6007-000043"] /*多语: 保存成功！*/
            });
            this.setState({
                pkHrSort: res.data.pkHrSort
            });
            return res;
        });
    }

    addOneRow() {

        const {
            table,
            templateId
        } = this.props;
        let {
            selectedField,
            allFields,
            selectedAscendFlag,
            language
        } = this.state;

        let selectedFieldObject = allFields.filter(item => item.value === selectedField);

        let rowData = {
            field_code: {
                display: selectedFieldObject[0].title,
                value: selectedFieldObject[0].value,
                scale: -1
            },
            ascend_flag: {
                display: selectedAscendFlag ? language['hi6007-000018'] : language['hi6007-000019'],/* 国际化处理： 升序,降序*/
                value: selectedAscendFlag,
                scale: -1
            }
        };
        let isExist = false;

        this.tableData.rows.map((item) => {
            if (item.values.field_code.value === selectedField) {
                isExist = true;
            }
        });

        if (isExist === false) {
            this.tableData.rows.push({
                values: rowData
            });
        }

        table.setAllTableData(templateId, this.tableData)

    }

    selectChangeHandle(type) {
        return (value) => {
            let field = type === 'field' ? 'selectedField' : 'selectedAscendFlag';

            this.setState({
                [field]: value
            });
        }
    }

    showModalHandle() {
        // if (onceInit === false) {
        //     this.processTemplate();
        //     onceInit = true;
        // }

        this.getTableData();
    }

    getTableData() {
        const {templateId, func_type, table} = this.props;
        initSortData({
            func_type: func_type
        })
            .then((res) => {
                if (res.success) {
                    let tableData = this.processTableData(res.data.defaultFields);
                    let allFields = this.processAllFields(res.data.allFields);

                    this.tableData = tableData;

                    table.setAllTableData(templateId, tableData)
                    console.log(table.getAllTableData(templateId))
                    this.setState({
                        allFields: allFields,
                        selectedField: allFields[0].value,
                        pkHrSort: res.data.pkHrSort
                    });
                }
            });
    }

    processAllFields(data) {
        let result = [];

        data.map((item) => {
            result.push({
                value: item.code,
                title: item.name
            });
        });

        return result;
    }

    processTableData(data) {
        const {language} = this.state;
        let result = {
            areacode: this.props.templateId,
            rows: []
        };

        data.map((item) => {
            result.rows.push({
                values: {
                    field_code: {
                        display: item.field_name,
                        value: item.field_code,
                        scale: -1
                    },
                    ascend_flag: {
                        value: item.ascend_flag,
                        display: item.ascend_flag ? language['hi6007-000018'] : language['hi6007-000019'],/* 国际化处理： 升序,降序*/
                        scale: -1
                    }
                }
            });
        });
        return result;
    }

    closeModal() {
        this.props.onClose && this.props.onClose();
    }


    render() {
        const {visible, table, templateId, editTable} = this.props;
        const {
            allFields,
            selectedAscendFlag,
            selectedField,
            language
        } = this.state;

        return (
            <NCModal
                show={visible}
                className="sort-modal-wrapper"
                size="sm"
                onHide={this.closeModal}
                onEntered={this.showModalHandle}
                backdrop="static"
            >
                <NCModalHeader
                    closeButton={true}
                >
                    {language['hi6007-000026']}{/* 国际化处理： 排序*/}
                </NCModalHeader>
                <NCModalBody>
                    <div className="sort-modal-content">
                        <label className="sort-modal-label">{language['hi6007-000027']}</label>{/* 国际化处理： 排序方式*/}
                        <NCSelect
                            className="sort-modal-select"
                            value={selectedField}
                            onChange={this.selectChangeHandle('field')}
                        >
                            {allFields.map((item) => {
                                return (
                                    <NCOption
                                        value={item.value}
                                    >
                                        {item.title}
                                    </NCOption>
                                );
                            })}
                        </NCSelect>
                        <NCSelect
                            className="sort-type-select"
                            value={selectedAscendFlag}
                            onChange={this.selectChangeHandle('type')}
                        >
                            <NCOption
                                value={true}
                            >
                                {language['hi6007-000018']}{/* 国际化处理： 升序*/}
                            </NCOption>
                            <NCOption
                                value={false}
                            >
                                {language['hi6007-000019']}{/* 国际化处理： 降序*/}
                            </NCOption>
                        </NCSelect>
                        <div className="sort-modal-button-wrapper">
                            <NCButton
                                colors="border"
                                onClick={this.addOneRow}
                            >
                                {language['hi6007-000028']}{/* 国际化处理： 增加*/}
                            </NCButton>
                        </div>
                        <div className="sort-modal-table">
                            {table.createSimpleTable(templateId, {
                                cancelCustomRightMenu: true
                            })}
                        </div>
                    </div>
                </NCModalBody>

                <NCModalFooter>
                    <NCPopconfirm
                        trigger="click"
                        placement="top"
                        content={language['hi6007-000021']}/* 国际化处理： 是否清空数据库中保存的排序条件？*/
                        onClose={this.cleanTable}
                        className="sort-modal-confirm-pop"
                    >
                        <NCButton
                            shape="border"
                            className="sort-clean-btn"
                            style={{
                                position: 'relative',
                                top: '8px'
                            }}
                        >
                            {language['hi6007-000029']}{/* 国际化处理： 清空*/}
                        </NCButton>
                    </NCPopconfirm>
                    <NCButton
                        className="sort-btn-2"
                        colors="primary"
                        onClick={this.beSure}
                    >
                        {language['hi6007-000030']}{/* 国际化处理： 确认*/}
                    </NCButton>
                    <NCButton
                        className="sort-btn-2"
                        shape="border"
                        onClick={this.saveSort}
                    >
                        {language['hi6007-000031']}{/* 国际化处理： 保存*/}
                    </NCButton>
                    <NCButton
                        className="sort-btn-2"
                        shape="border"
                        onClick={this.closeModal}
                    >
                        {language['hi6007-000003']}{/* 国际化处理： 取消*/}
                    </NCButton>
                </NCModalFooter>
            </NCModal>
        );
    }
}

export default SortModal;
